package com.joelaws.prototype.client;

import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.ToolbarTextItem;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.layout.FitLayout;
import com.joelaws.prototype.client.data.User;
import com.joelaws.prototype.client.manage.ManagePanel;
import com.joelaws.prototype.client.service.ServicePanel;

public class TopPanel extends Panel {

	private final ToolbarButton login;

	private final ToolbarButton register;

	private final ToolbarButton home;

	private final ToolbarButton manage;

	private final ToolbarButton logout;

	private User user;

	public TopPanel() {

		setBorder(false);
		setLayout(new FitLayout());

		ToolbarTextItem companyName = new ToolbarTextItem("J&P Entertainment");

		register = new ToolbarButton("[Register]");
		login = new ToolbarButton("[Login]");
		home = new ToolbarButton("[Home]");
		manage = new ToolbarButton("[Manage Account]");
		logout = new ToolbarButton("[Logout]");

		ButtonListenerAdapter listener = new ButtonListenerAdapter() {

			public void onClick(Button button, EventObject e) {
				if (button == register) {
					System.out.println("Register me");
					ScreenManager.instance().showScreen(new RegisterPanel());
				} else if (button == login) {
					System.out.println("Log me in");
					ScreenManager.instance().showScreen(new LoginPanel());
				} else if (button == home) {
					System.out.println("Home me");
					ScreenManager.instance().showScreen(new ServicePanel(user));
				} else if (button == manage) {
					System.out.println("Manage me");
					ScreenManager.instance().showScreen(new ManagePanel(user));
				} else if (button == logout) {
					ScreenManager.instance().setLoggedOut();
					System.out.println("Log me out");
				} else {
					System.out.println("Unknown button");
				}
			}
		};

		register.addListener(listener);
		login.addListener(listener);
		home.addListener(listener);
		manage.addListener(listener);
		logout.addListener(listener);

		Toolbar toolbar = new Toolbar();
		toolbar.addItem(companyName);
		toolbar.addFill();
		toolbar.addButton(register);
		toolbar.addButton(login);
		toolbar.addButton(home);
		toolbar.addButton(manage);
		toolbar.addButton(logout);

		setTopToolbar(toolbar);
	}

	public void setLoggedOut() {
		user = null;
		register.show();
		login.show();
		home.hide();
		manage.hide();
		logout.hide();
		doLayout();
	}

	public void setLoggedIn(User user) {
		this.user = user;
		register.hide();
		login.hide();
		home.show();
		manage.show();
		logout.show();
		doLayout();
	}

}
